package com.module.home.utils

import android.util.Log
import com.common.app.data.bean.KeyEvents.KEY_HOME_UP_STATS_COMPLETED
import com.common.base.app.extras.yes
import com.jeremyliao.liveeventbus.LiveEventBus
import com.module.home.data.bean.UploadRequestTracker

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/09/15
 *
 * 描述：管理整个会话的统计信息
 *
 * 修订历史：
 *
 */
class UploadStatistics {
    private val requests = mutableMapOf<String, UploadRequestTracker>()
    private var sessionId: String = ""
    private var expectedRequestCount: Int = 0
    private var actualRequestCount: Int = 0

    fun startNewSession(): String {
        sessionId = "session_${System.currentTimeMillis()}"
        requests.clear()
        expectedRequestCount = 0
        actualRequestCount = 0
        Log.d("UploadStats", "开始新的上传统计会话: $sessionId")
        return sessionId
    }

    fun setExpectedRequestCount(count: Int) {
        expectedRequestCount = count
        Log.d("UploadStats", "预期请求数量: $count")
        checkSessionComplete()
    }

    fun addRequest(requestId: String, dataType: String, dataSize: Int) {
        requests[requestId] = UploadRequestTracker(requestId, dataType, dataSize)
        actualRequestCount++
        Log.d("UploadStats", "添加上传请求: $requestId, 类型: $dataType, 数量: $dataSize (${actualRequestCount}/${expectedRequestCount})")
    }

    fun markCompleted(requestId: String, isSuccess: Boolean) {
        requests[requestId]?.let {
            it.isCompleted = true
            it.isSuccess = isSuccess
            Log.d("UploadStats", "请求完成: $requestId, 成功: $isSuccess")
            checkSessionComplete()
        }
    }

    private fun checkSessionComplete() {
        // 只有当实际请求数达到预期数量，且所有请求都完成时，才算会话完成
        if (expectedRequestCount > 0 &&
            actualRequestCount == expectedRequestCount &&
            requests.isNotEmpty() &&
            requests.all { it.value.isCompleted }) {

            val successCount = requests.count { it.value.isSuccess }
            val totalCount = requests.size
            Log.i("UploadStats", "会话 $sessionId 所有请求完成: 成功 $successCount/$totalCount")

            onAllRequestsCompleted(successCount, totalCount)
        }
    }

    private fun onAllRequestsCompleted(successCount: Int, totalCount: Int) {
        val successRate = if (totalCount > 0) (successCount * 100 / totalCount) else 0
        Log.i("UploadStats", "本次 findAllClassData 执行完成，上传成功率: $successRate% ($successCount/$totalCount)")

        (totalCount <= successCount).yes{
            // 可以发送事件或显示通知
            LiveEventBus.get(KEY_HOME_UP_STATS_COMPLETED).post(this)
        }
    }
}